package com.cn.ycy.controller;

import com.cn.ycy.dto.ReturnT;
import com.cn.ycy.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/cookie")
public class CookieController {

  static Logger logger = LoggerFactory.getLogger(CookieController.class);

    /**
     * 前端如果是跨站请求，服务器端 setCookie会失效
     * @param userId
     * @param httpServletRequest
     * @param response
     * @return
     */
  @RequestMapping(value = "/setcookie", method = RequestMethod.GET)
  @ResponseBody
  public ReturnT<User> setCookie(@RequestParam("userId") int userId
          , HttpServletRequest httpServletRequest, HttpServletResponse response) {
    logger.info("userId {}", userId);
    User user = new User();
    user.setUsername("小张");
    //添加attribute
    httpServletRequest.setAttribute("haha", "user_attribute");

    //添加cookie
    Cookie cookie = new Cookie("haha" + userId, "user_haha" + userId);
    cookie.setMaxAge(60);
    response.addCookie(cookie);
    return new ReturnT<User>(user);
  }

}
